import moment from 'moment';
import { request } from 'umi';
import qs from 'qs';

// 通过id递归出中文
export const getTextbyIdsFromJSon = (
  json,
  ids,
  { key = 'label', value = 'value', children = 'children' } = {},
) => {
  let obj = json;
  const result: any[] = [];
  if (Array.isArray(ids) && ids.length > 0) {
    ids.forEach((id) => {
      const item = obj.find((item2) => item2[value] === id);
      if (item) {
        result.push(item[key]);
      }
      if (item && item[children]) {
        obj = item[children];
      }
    });
  }
  return result;
};

export const uid = (len = 8, radix = 16): string => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  const value: string[] = [];
  const newRadix = radix || chars.length;

  if (len) {
    // Compact form
    for (let i = 0; i < len; i += 1) {
      // eslint-disable-next-line no-bitwise
      value[i] = chars[0 | (Math.random() * newRadix)];
    }
  } else {
    // rfc4122, version 4 form
    let r;

    // rfc4122 requires these characters
    /* eslint-disable-next-line */
    value[8] = value[13] = value[18] = value[23] = '-';
    value[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (let i = 0; i < 36; i += 1) {
      if (!value[i]) {
        // eslint-disable-next-line no-bitwise
        r = 0 | (Math.random() * 16);
        // eslint-disable-next-line no-bitwise
        value[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return value.join('');
};

export const downLoad = (url, { fileName }) =>
  request(url, {
    method: 'get',
    responseType: 'blob', // 代表内存之中的一段为二进制
    getResponse: true,
  }).then((data) => {
    const blob = data.data;
    const disposition = data.response.headers.get('Content-Disposition');
    const _fileName = disposition
      ? decodeURI(disposition.split(';')[1].split('filename=')[1])
      : fileName;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(new Blob([blob]));
    link.download = _fileName;
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
  });

export const loadScript = (src) => {
  const headElement = document.head || document.getElementsByTagName('head')[0];
  const _importedScript = {};

  return new Promise((resolve, reject) => {
    if (src in _importedScript) {
      resolve(true);
      return;
    }
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.onerror = (err) => {
      headElement.removeChild(script);
      reject(new URIError(`The Script ${src} is no accessible.`));
    };
    script.onload = () => {
      _importedScript[src] = true;
      resolve(false);
    };
    headElement.appendChild(script);
    script.src = src;
  });
};

export const isImg = (name) => {
  const arr = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  const index = name?.lastIndexOf?.('.');
  const suffix = name?.slice?.(index);
  return arr.includes(suffix) || name?.includes?.('base64');
};
export const isVideo = (name) => {
  const arr = ['.avi', '.mp4', '.mov'];
  const index = name?.lastIndexOf('.');
  const suffix = name?.slice(index);
  return arr.includes(suffix?.toLocaleLowerCase());
};

export const isRAR = (name) => {
  const arr = ['.zip', '.rar'];
  const index = name?.lastIndexOf('.');
  const suffix = name?.slice(index);
  return arr.includes(suffix);
};

export const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

export const formatObjToAntList = (obj) => {
  return Object.keys(obj).reduce((pre: any[], cur) => {
    pre.push({
      label: obj[cur],
      value: cur,
    });
    return pre;
  }, []);
};

/**
 * 递归把扁平数据变成tree数据
 * @explams
 * arr2Tree([{parentId: 0, ....}])
 */
export const arr2Tree = (oldData: any[] = [], value = undefined, newData: any[] = []) => {
  oldData.forEach((item) => {
    if (item.parentId === value) {
      newData.push(item);
      delete item.parentId;
    }
  });
  newData.forEach((i) => {
    i.children = [];
    arr2Tree(oldData, i.value, i.children);
    i.children.length || delete i.children;
  });
  return newData;
};

export const flatArray = (arr = [], children = 'children') => {
  return arr.reduce((pre, cur: any) => {
    if (cur[children]) {
      pre.push(...flatArray(cur[children]));
      pre.push({ ...cur, [children]: undefined });
    } else {
      pre.push(cur);
    }
    return pre;
  }, [] as any[]);
};

export const calcIndex = (data: any[] = []) => {
  let index = 1;
  const list = JSON.parse(JSON.stringify(data));
  list.forEach((record) => {
    if (record.children) {
      record.children.forEach((it) => {
        it.index = index;
        index += 1;
      });
    } else {
      record.index = index;
      index += 1;
    }
  });
  return list;
};

// 格式化时间到零点前一秒
export const formatDateBeForeZeroPoint = (value) => {
  const result = moment(value).isValid()
    ? moment(moment(value).format('YYYY-MM-DD 23:59:59')).valueOf()
    : null;
  return result;
};

export const locationHrefAddQuerys = (data = {}) => {
  const { search, origin, pathname } = window.location;
  const query = qs.parse(search?.split('?')?.[1]);
  const newQueryString = qs.stringify({ ...query, ...data });
  return `${origin}${pathname}?${newQueryString}`;
};

// 是否是预售课
export const isYsClass = (data) => {
  const flag =
    data?.bookprice && data?.bookdead && moment(data.bookdead, 'X').isSameOrAfter(moment())
      ? true
      : false;
  return flag;
};

export const formatSizeUnits = (kb) => {
  if (kb === undefined) return '-';
  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  let unitIndex = 0;

  while (kb >= 1024 && unitIndex < units.length - 1) {
    kb /= 1024;
    unitIndex++;
  }

  return `${kb.toFixed(2)} ${units[unitIndex]}`;
};
